package com.zhl.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * Created by Administrator on 2019/4/18.
 */
@Configuration
@MapperScan(basePackages = {"com.zhl.dao.cm"},sqlSessionFactoryRef = "cmSqlSessionFactory")
public class CmDBConfig {

    @Resource
    @Qualifier("cmDS")
    private DataSource cmDS;

    @Bean(name = "cmSqlSessionFactory")
    public SqlSessionFactory cmSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(cmDS);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/cm/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "cmTransactionManager")
    @Primary
    public DataSourceTransactionManager cmTransactionManager() {
        return new DataSourceTransactionManager(cmDS);
    }

    @Bean(name = "cmSqlSessionTemplate")
    public SqlSessionTemplate cmSqlSessionTemplate(@Qualifier("cmSqlSessionFactory")  SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
